package org.framework.lazy.cloud.network.heartbeat.server.netty.flow.proxy;

import io.netty.channel.Channel;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.flow.proxy.AbstractHandleChannelProxyFlowAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.flow.proxy.ChannelProxyFlow;
import org.framework.lazy.cloud.network.heartbeat.common.enums.ChannelFlowEnum;
import org.framework.lazy.cloud.network.heartbeat.common.enums.ChannelProtocolType;
import org.framework.lazy.cloud.network.heartbeat.common.enums.ChannelProxyType;
import org.framework.lazy.cloud.network.heartbeat.server.properties.ServerNodeProperties;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.LazyProxyFlowApplication;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.command.lazy.proxy.flow.LazyProxyFlowStoryCommand;

/**
 * 进口流量处理
 */
public class ServerHandlerInProxyFlowHandler extends AbstractHandleChannelProxyFlowAdvanced {

    private final LazyProxyFlowApplication lazyProxyFlowApplication;
    private final ServerNodeProperties serverNodeProperties;

    public ServerHandlerInProxyFlowHandler(LazyProxyFlowApplication lazyProxyFlowApplication, ServerNodeProperties serverNodeProperties) {
        this.lazyProxyFlowApplication = lazyProxyFlowApplication;
        this.serverNodeProperties = serverNodeProperties;
    }

    /**
     * 处理是否支持这种类型
     *
     * @param channelProxyFlow 数据
     * @return boolean
     */
    @Override
    protected boolean doSupport(ChannelProxyFlow channelProxyFlow) {
        if (serverNodeProperties.getEnableFlowControl()) {
            return ChannelFlowEnum.IN_FLOW.equals(channelProxyFlow.channelFlowEnum());
        } else {
            return false;
        }
    }

    /**
     * 处理当前数据
     *
     * @param channel          当前通道
     * @param channelProxyFlow 通道数据
     */
    @Override
    protected void doHandler(Channel channel, ChannelProxyFlow channelProxyFlow) {
        String clientId = channelProxyFlow.clientId();
        String ip = channelProxyFlow.ip();
        Integer port = channelProxyFlow.port();
        Integer flow = channelProxyFlow.flow();
        ChannelProtocolType channelProtocolType = channelProxyFlow.channelProtocolType();
        ChannelProxyType channelProxyType = channelProxyFlow.channelProxyType();

        // TODO
        // 进口流量处理
        LazyProxyFlowStoryCommand lazyProxyFlowStoryCommand = new LazyProxyFlowStoryCommand();
        lazyProxyFlowStoryCommand.setInFlow(flow);
        lazyProxyFlowStoryCommand.setClientId(clientId);
        lazyProxyFlowStoryCommand.setIp(ip);
        lazyProxyFlowStoryCommand.setPort(port);
        lazyProxyFlowStoryCommand.setProtocolType(channelProtocolType);
        lazyProxyFlowStoryCommand.setProxyType(channelProxyType);

        lazyProxyFlowStoryCommand.setIsDeleted(false);
        lazyProxyFlowApplication.flowIncreaseStory(lazyProxyFlowStoryCommand);

    }
}
